import gi
gi.require_version('Gst', '1.0')
from gi.repository import Gst

class Player:
    def __init__(self):
        Gst.init(None)
        self.player = Gst.ElementFactory.make("playbin", "player")
        self.bus = self.player.get_bus()
        self.bus.add_signal_watch()
        self.bus.connect("message", self._on_message)
        
        self._volume = 1.0
        self.current_station = None
    
    def _on_message(self, bus, message):
        if message.type == Gst.MessageType.ERROR:
            err, debug = message.parse_error()
            print(f"Error: {err}, {debug}")
            self.stop()
    
    def play(self, station):
        if station and station.get('url'):
            self.current_station = station
            self.player.set_property("uri", station['url'])
            self.player.set_state(Gst.State.PLAYING)
    
    def stop(self):
        self.player.set_state(Gst.State.NULL)
    
    def pause(self):
        self.player.set_state(Gst.State.PAUSED)
    
    def resume(self):
        self.player.set_state(Gst.State.PLAYING)
    
    @property
    def volume(self):
        return self._volume
    
    @volume.setter
    def volume(self, value):
        self._volume = max(0.0, min(1.0, value))
        self.player.set_property("volume", self._volume)
    
    def is_playing(self):
        _, state, _ = self.player.get_state(Gst.CLOCK_TIME_NONE)
        return state == Gst.State.PLAYING